package org.jmeter.tcp.helmet.gps;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.jmeter.tcp.util.HttpUtil;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/11/26 16:19
 * @since
 */
public class HttpGpsPushTask extends GpsPushTask {

    CloseableHttpClient httpClient = null;

    private String address;

    public HttpGpsPushTask(ScheduledExecutorService executorService, String imei, List<Gps> gpsList,
                           String address) {
        super(executorService, imei, gpsList);
        this.address = address;

        // 创建客户端
        httpClient = HttpClients.createDefault();
    }


    @Override
    public void pushGps(List<Gps> willPushGps) {
        // 组装数据
        String content = convertData(willPushGps);
        log.info("当前推送开始"+(start - batchSize)+"，共"+willPushGps.size()+"条："+content);

        // 执行请求
        HttpPost post = new HttpPost(address);
        post.setHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity entity = new StringEntity(content, "UTF-8");
        post.setEntity(entity);
        try {
            CloseableHttpResponse response =  httpClient.execute(post);
            byte[] bytes = HttpUtil.parseResponse(response);
            if(bytes != null){
                log.info("push gps response:" + new String(bytes));
            }
        } catch (ClientProtocolException e) {
            log.error("http post error, url is : %s", e);
        } catch (IOException e) {
            log.error("http post error", e);
        }
    }

    private String convertData(List<Gps> willPushGps) {
        // 组装数据
        JSONObject json = new JSONObject();
        json.put("t", 10);
        json.put("e", imei);

        JSONArray gpsList = new JSONArray();
        for (Gps gps : willPushGps) {
            JSONObject g = new JSONObject();
            g.put("s", "1"); // s为1则包含gps数据
            g.put("g", gps.getStar()); // 搜星数量
            g.put("x", gps.getLng());
            g.put("y", gps.getLat());
            g.put("zs", gps.getZs());
            g.put("ys", gps.getYs());
            g.put("xs", gps.getXs());
            g.put("time", gps.getLocationTime().getTime());
            gpsList.add(g);
        }
        json.put("n", gpsList);

        return json.toJSONString();
    }


}
